package demo;

import org.junit.Test;

/**
 * RunnableDemo
 *
 * @author chisheng
 */
public class RunnableDemo {

    /* The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
     * The class must define a method of no arguments called run. */

    @Test
    public void testRunnable() {
        final MyRunable runable = new MyRunable();

        /* public Thread(Runnable target)
         *  Allocates a new Thread object.
         *  This constructor has the same effect as Thread (null, target, gname),
         *  where gname is a newly generated name.
         *  Automatically generated names are of the form "Thread-"+n,
         *  where n is an integer.
         *
         * runable: the object whose run method is invoked when this thread is started.
         *          If null, this classes run method does nothing */
        final Thread thread0 = new Thread(runable);
        final Thread thread1 = new Thread(runable);
        final Thread thread2 = new Thread(runable);

        /* public synchronized void start()
         *  Causes this thread to begin execution;
         *  the Java Virtual Machine calls the run method of this thread.
         *  The result is that two threads are running concurrently:
         *  the current thread (which returns from the call to the start method)
         *  and the other thread (which executes its run method). */
        thread0.start();
        thread1.start();
        thread2.start();
    }

    private static class MyRunable implements Runnable {
        @Override
        public void run() {
            /* public static native Thread currentThread()
             *  Returns a reference to the currently executing thread object.
             *
             * public final String getName()
             *  Returns this thread's name.
             */
            System.out.println(Thread.currentThread().getName() + " is running now.");
        }
    }

}
